// 用户相关
import { getUserInfo, login } from '@/api/user'

import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

const state = {
  token: getToken(),
  info: {}, // 个人信息
}
const getters = {}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data, status } = response
          //status为0登录成功
          if (status === 0) {
            commit('SET_TOKEN', data)
            setToken(data)
            resolve()
          } else {
            reject(response)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 调取登出接口
      commit('SET_TOKEN', '') // 清除token
      commit('SET_INFO', {}) // 清除用户信息
      removeToken()
      resolve()
    })
  },
  // 获取用户信息
  getInfo({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      // 调取接口获取用户信息
      getUserInfo()
        .then((response) => {
          const { data } = response
          const localUserList = localStorage.getItem('localUserList')
            ? JSON.parse(localStorage.getItem('localUserList'))
            : []
          const index = localUserList.findIndex((item) => item.userId === data.userId)

          if (index < 0) {
            localUserList.push(data)
            localStorage.setItem('localUserList', JSON.stringify(localUserList))
            if (localUserList.length >= 2) {
              localStorage.removeItem('localUserList')
              router.push({ path: '/home' })
            }
          }

          commit('SET_INFO', data)
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
}

export default {
  namespaced: true, // 开启命名空间模块
  state,
  getters,
  mutations,
  actions,
}
